<template>
  <Modal
    v-model="visible"
    title="历史患者列表"
    width="900"
    :mask-closable="false"
  >
    <div class="search-bar">
      <Input
        v-model="searchKey"
        placeholder="请输入患者姓名/手机号"
        style="width: 200px; margin-right: 10px"
      />
      <Button type="primary" icon="ios-search" @click="handleSearch">搜索</Button>
      <Button style="margin-left: 10px" @click="handleReset">重置</Button>
    </div>

    <Table :loading="loading" :columns="columns" :data="patientList" style="margin-top: 10px">
      <template slot-scope="{ row }" slot="action">
        <Button
          type="primary"
          size="small"
          style="margin-right: 5px"
          @click="viewMedicalRecords(row)"
        >
          查看病历
        </Button>
      </template>
    </Table>

    <div class="page-wrapper">
      <Page
        :total="total"
        :current="searchForm.pageNumber"
        :page-size="searchForm.pageSize"
        show-total
        show-elevator
        @on-change="handlePageChange"
      />
    </div>

    <div slot="footer">
      <Button @click="handleClose">关闭</Button>
    </div>
  </Modal>
</template>

<script>
import { getPatientList } from '@/api/medical-dashboard'
import { mapGetters } from 'vuex'

export default {
  name: 'PatientListModal',
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapGetters(['userId', 'doctorId'])
  },
  data() {
    return {
      visible: this.value,
      loading: false,
      searchKey: '',
      total: 0,
      patientList: [],
      searchForm: {
        pageNumber: 1,
        pageSize: 10
      },
      columns: [
        {
          title: '姓名',
          key: 'name',
          width: 100
        },
        {
          title: '性别',
          key: 'sex',
          width: 80,
          render: (h, params) => {
            return h('span', params.row.sex === '男' ? '男' : '女')
          }
        },
        {
          title: '年龄',
          key: 'age',
          width: 80
        },
        {
          title: '手机号',
          key: 'mobile',
          width: 120
        },
        {
          title: '就诊次数',
          key: 'visitCount',
          width: 100
        },
        {
          title: '最近就诊时间',
          key: 'lastVisitTime',
          width: 160
        },
        {
          title: '主要诊断',
          key: 'lastDiagnosis',
          width: 200
        },
        {
          title: '操作',
          slot: 'action',
          width: 100,
          align: 'center'
        }
      ]
    }
  },
  watch: {
    value(val) {
      this.visible = val
      if (val) {
        this.loadPatientList()
      }
    },
    visible(val) {
      this.$emit('input', val)
      if (!val) {
        this.handleReset()
      }
    }
  },
  methods: {
    async loadPatientList() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          searchKey: this.searchKey,
          doctorId: this.doctorId || this.userId
        }
        console.log('加载患者列表，参数:', params);
        const res = await getPatientList(params)
        console.log('获取患者列表响应:', res);
        if (res.success) {
          this.patientList = (res.result.records || []).map(patient => ({
            id: patient.id,
            name: patient.name || patient.nickname || '未知',
            sex: patient.sex || patient.gender || '未知',
            age: patient.age || '未知',
            mobile: patient.mobile || patient.phone || '未知',
            visitCount: patient.visitCount || 0,
            lastVisitTime: patient.lastVisitTime || '暂无记录',
            lastDiagnosis: patient.lastDiagnosis || '暂无诊断'
          }))
          this.total = res.result.total || 0
        } else {
          this.$Message.error(res.message || '获取患者列表失败')
        }
      } catch (error) {
        console.error('获取患者列表失败:', error)
        this.$Message.error('获取患者列表失败')
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.searchForm.pageNumber = 1
      this.loadPatientList()
    },
    handleReset() {
      this.searchKey = ''
      this.searchForm.pageNumber = 1
      this.loadPatientList()
    },
    handlePageChange(page) {
      this.searchForm.pageNumber = page
      this.loadPatientList()
    },
    handleClose() {
      this.visible = false
    },
    viewMedicalRecords(patient) {
      this.$router.push({
        path: `/medical-records/${patient.id}`,
        query: { 
          patientName: patient.name,
          patientId: patient.id
        }
      })
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
.search-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.page-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style> 